package com.example.usermanagement.config;

import cn.hutool.core.date.DateUtil;
import com.example.usermanagement.handle.GlobalExceptionHandler;
import com.example.usermanagement.utils.LocaTimeToDateUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.InstantSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * @author yha
 * @ClassName
 * @description:TODO
 * @date 2024年09月10日
 * @version: 1.0.0
 */
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
@Import({GlobalExceptionHandler.class})
public class JsonConfiguration {



    /**处理对象属性为空时，用空字符串替代空值*/
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return objectMapper;
    }


    /**
     * 配置FastJson方式二
     *
     * @return HttpMessageConverters
     */
    @Bean(name = "getMappingJackson2HttpMessageConverter")
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(smt);
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));



        objectMapper.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);

        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, IOException {
//                     jsonGenerator.writeString("");
                if(o instanceof Long){
                    jsonGenerator.writeString(String.valueOf(o));
                }
                if(o instanceof BigDecimal){
                    jsonGenerator.writeString(new DecimalFormat("0.##").format(o));
                }
                if(o instanceof LocalDateTime){
                    Date a = LocaTimeToDateUtil.localDateTimeToDate((LocalDateTime) o);
                    jsonGenerator.writeString(DateUtil.format(a,"yyyy-MM-dd HH:mm:ss"));
                }
                if(o instanceof Date){
                    jsonGenerator.writeString(DateUtil.format(Date.class.cast(o),"yyyy-MM-dd HH:mm:ss"));
                }
            }
        });
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

        //设置中文编码格式
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        list.add(MediaType.TEXT_HTML);
        list.add(MediaType.TEXT_PLAIN);
        list.add(MediaType.IMAGE_GIF);
        list.add(MediaType.IMAGE_PNG);
        list.add(MediaType.IMAGE_JPEG);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
    }

//    private class JavaTimeModule extends SimpleModule {
//        public JavaTimeModule(){
//            //======================Long类型序列化规则=========================
//            this.addSerializer(Long.class, ToStringSerializer.instance);
//            this.addSerializer(Long.TYPE,ToStringSerializer.instance);
//            // ======================= 时间序列化规则 ===============================
//            this.addDeserializer(Date.class, DateDeserializers.DateDeserializer.instance);
//            // yyyy-MM-dd HH:mm:ss
//            this.addSerializer(LocalDateTime.class,
//                    new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//            // yyyy-MM-dd
//            this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
//            // HH:mm:ss
//            this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ISO_LOCAL_TIME));
//            // Instant 类型序列化
//            this.addSerializer(Instant.class, InstantSerializer.INSTANCE);
//
//            // ======================= 时间反序列化规则 ==============================
//            // yyyy-MM-dd HH:mm:ss
//            this.addDeserializer(LocalDateTime.class,
//                    new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//            // yyyy-MM-dd
//            this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
//            // HH:mm:ss
//            this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
//            // Instant 反序列化
//            this.addDeserializer(Instant.class, InstantDeserializer.INSTANT);
//
//
//        }}
}
